package moonhy.c2dm_client;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import moonhy.c2dm_client.dw.NoticeData;
import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;


public class NoticeListActivity extends Activity{
	private LinkedList<NoticeData> noticeJsonData = new LinkedList<NoticeData>();
	
	private ListView noticeListView;
	private LinearLayout loadingBarLayout;
	private SharedPreferences prefs;
	private noticeListAdapter noticeAdapter;
	private OnSharedPreferenceChangeListener listener;
	private ProgressBar dialog;
	
	int pageNo		= 0;
	int pageSize	= 10;
	int savedFirstVisibleItem = -1;
	boolean firstPrevItemLoading = true;
	boolean isFinishedLoading = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notice_listview_main);
		
		noticeListView = (ListView)findViewById(R.id.listviewNoticeList);
		//noticeListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		//noticeListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
        
		dialog = (ProgressBar) findViewById(R.id.noticeProgressBar);
		dialog.setVisibility(View.INVISIBLE);
		
		//new initPage(this).execute();
		
		
		
		
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "noticeInfo");
			
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				NoticeData mList = new NoticeData(jsonObject.getInt("seqno"), jsonObject.getString("title")
						,jsonObject.getString("name"), jsonObject.getString("content")
						,jsonObject.getString("reg_date"), jsonObject.getString("reg_check")
				);
				noticeJsonData.add(mList);
				Log.d("C2DM", "Init Data: " + jsonObject.getInt("seqno"));
			}
			
//			if(json_result == null || json_result.length() == 0){
//				new getNewNotice(this).execute();
//			}
			
//			if(json_result == null || json_result.length() ==0 )
//				setData(this);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		loadingBarLayout = (LinearLayout) View.inflate(this, R.layout.notice_listview_loading, null);
        loadingBarLayout.setVisibility(View.INVISIBLE);
        noticeListView.addHeaderView(loadingBarLayout);
		
		noticeAdapter = new noticeListAdapter(this, R.layout.notice_listview_layout, noticeJsonData);
		noticeListView.setAdapter(noticeAdapter);
		
		
		noticeListView.setOnScrollListener(new OnScrollListener() {
			
			// @Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}
			
			// @Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
//				Log.v("C2DM", "onScroll");
//				Log.v("C2DM", "firstVisibleItem = " + firstVisibleItem);
//				Log.v("C2DM", "visibleItemCount = " + visibleItemCount);
//				Log.v("C2DM", "totalItemCount = " + totalItemCount);
				
				if(totalItemCount > pageSize && firstVisibleItem == 0 && !isFinishedLoading){
					if(savedFirstVisibleItem != firstVisibleItem){
						Log.e("C2DM", "firstVisibleItem = " + firstVisibleItem + "  isFinishedLoading" + isFinishedLoading);
						if(loadingBarLayout.getVisibility() == View.INVISIBLE){
							new getPrevNotice(getApplicationContext()).execute();
						}
					}
				}else{
				}
				
				savedFirstVisibleItem = firstVisibleItem;
				
				/*if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
					Log.v("C2DM", "IN, totalItemCount = " + totalItemCount);
					if (totalListNum > itemNum) {
						mTestLayout.setVisibility(View.VISIBLE);
						new getMoreItems().execute(Items);
					} else {
						mTestLayout.setVisibility(View.INVISIBLE);
					}
					Log.v("C2DM", "IN END");
				}*/
			}
		});
		
		
		noticeListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.d("C2DM", "Clicked" + position);
				//view.setBackgroundColor(0x00);
				//noticeListView.getChildAt(position).setBackgroundColor(0xFFFF0000);
            }
        });
		
		
		
		listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
			@Override
			public void onSharedPreferenceChanged(SharedPreferences arg0, String key) {

				if (key.equalsIgnoreCase("noticeMaxSeqno")) {

					Log.i("C2DM", "onSharedPreferenceChanged ====================");
					//Toast.makeText(getApplicationContext(), "onSharedPreferenceChanged", Toast.LENGTH_LONG).show();
					int currentSeqno = arg0.getInt("noticeSeqno", 0);
                   
					// DB 다녀오겠습니다~
					new getNewNotice(getApplicationContext()).execute();
				}
			}
		};
		prefs.registerOnSharedPreferenceChangeListener(listener);
		
		
//		noticeJsonData.clear();
		new getNewNotice(this).execute();
		
		/*
		Intent extras = getIntent();
		if (extras != null) {
			
//			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//			String cacheNotice = prefs.getString("cacheNotice", "");
//			WebView nWview = (WebView) findViewById(R.id.notification_view);
//			nWview.loadData(message, "text/html", null);
//			Editor edit = prefs.edit();
//			edit.putString("cacheNotice", cacheNotice + "\n\n" + message);
//			edit.commit();
			
			String message = extras.getStringExtra("payload");
			TextView view = (TextView) findViewById(R.id.result);

			if (message != null && message.length() > 0) {
				view.setText(message);
			}else{
				Log.d("C2DM", "removed");
				view.setText(message);
			}
		}
		
		
		final ProgressDialog dialog = ProgressDialog.show(this, "Loading", "Please wait...", true);
		dialog.setCancelable(true);
		dialog.setMax(100);
		dialog.show();
		 */
		
		
		/*
		ArrayList<NoticeData> nd_array = new ArrayList<NoticeData>();
		
		//String readNotice = readJSON("http://moonhy.mireene.com/kline/notice/notice_list.php");
		try {
			JSONArray jsonArray = new JSONArray(readJSON("http://moonhy.mireene.com/kline/notice/notice_list.php"));
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				
				NoticeData tmp_nd = new NoticeData();
				tmp_nd.setSeqno(jsonObject.getString("seqno"));
				tmp_nd.setTitle(jsonObject.getString("title"));
				tmp_nd.setContent(jsonObject.getString("content"));
				tmp_nd.setReg_date(jsonObject.getString("reg_date"));
				tmp_nd.setReg_Check(jsonObject.getString("reg_check"));
				nd_array.add(i, tmp_nd);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
		MyPagerAdapter adapter = new MyPagerAdapter(this, nd_array);
		viewPager.setAdapter(adapter);

		final TextView tvHeader = (TextView) findViewById(R.id.textViewHeader);
		tvHeader.setText("Page 1");
		
		//dialog.dismiss();
		*/
		
		
	}
	
	
	private void setData(Context context){
		//String readNotice = readJSON("http://moonhy.mireene.com/kline/notice/notice_list.php");
		try {
			httpConnectionManager hcm = new httpConnectionManager(context);
			JSONObject json = new JSONObject(hcm.readJSON(getString(R.string.SERVER_URL) + "notice/notice_list.php?pageno=0",null));
			
			JSONObject json_header = json.getJSONObject("header");
			JSONArray json_result = json.getJSONArray("data_result");
			
			JSONSharedPreferences.remove(context, "gline", "noticeInfo");
			JSONSharedPreferences.saveJSONArray(context, "gline", "noticeInfo", json_result);
			
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				NoticeData tmp_nd = new NoticeData();
				tmp_nd.setSeqno(jsonObject.getInt("seqno"));
				tmp_nd.setTitle(jsonObject.getString("title"));
				tmp_nd.setName(jsonObject.getString("name"));
				tmp_nd.setContent(jsonObject.getString("content"));
				tmp_nd.setReg_date(jsonObject.getString("reg_date"));
				tmp_nd.setReg_Check(jsonObject.getString("reg_check"));
				noticeJsonData.add(tmp_nd);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class initPage extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener{
		private Context context;
		
		private initPage(Context context){
			this.context = context;
		}

		@Override
		protected void onPreExecute(){
			dialog.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			JSONArray json_result;
			try {
				json_result = JSONSharedPreferences.loadJSONArray(context, "gline", "noticeInfo");
				
				for (int i = 0; i < json_result.length(); i++) {
					JSONObject jsonObject = json_result.getJSONObject(i);
					NoticeData mList = new NoticeData(jsonObject.getInt("seqno"), jsonObject.getString("title")
							,jsonObject.getString("name"), jsonObject.getString("content")
							,jsonObject.getString("reg_date"), jsonObject.getString("reg_check")
					);
					noticeJsonData.add(mList);
				}
				
				if(json_result == null || json_result.length() ==0 )
					setData(context);
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused)
        {
        	dialog.setVisibility(View.INVISIBLE);
        	
            noticeListView = (ListView)findViewById(R.id.listviewNoticeList);
            noticeListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
            
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            Editor edit = prefs.edit();
            if(noticeJsonData != null && noticeJsonData.size() > 0)
            	edit.putInt("noticeSeqno", noticeJsonData.get(noticeJsonData.size()-1).getSeqno()).commit();
            
            
            
    		/*
    		ArrayList<NoticeData> noticeJsonData = new ArrayList<NoticeData>();
    		
    		JSONArray json_result;
    		try {
    			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "memberInfo");
    			
    			for (int i = 0; i < json_result.length(); i++) {
    				JSONObject jsonObject = json_result.getJSONObject(i);
    				NoticeData mList = new NoticeData(jsonObject.getString("mem_name"), jsonObject.getString("mem_phone")
    						,jsonObject.getString("mem_email"), jsonObject.getString("mem_birth")
    						,jsonObject.getString("mem_desc")
    				); 
    				noticeJsonData.add(mList);
    			}
    		} catch (JSONException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		*/
    		
    		//ArrayAdapter<String> noticeAdapter = new ArrayAdapter<String>(this, R.layout.main_viewflow_sub3_listview_layout, noticeJsonData);
    		
    		
    		
    		
            /*
            Resources res = getResources();
    		Drawable shape = res.getDrawable(R.drawable.rounded_corner);
            
            LinearLayout mainNoticeView = (LinearLayout)findViewById(R.id.NoticeMainLayout);
            
            for(int i = 0 ; i < nd_array.size(); i++){
            	TextView regDateView = new TextView(context);
        		regDateView.setText("작성일: " + nd_array.get(i).getReg_date());
        		regDateView.setTextColor(0xFFFFFFFF);
        		regDateView.setTextSize(15);
        		
        		//regDateView.setBackgroundColor(0x99313029);
        		//regDateView.setPadding(20, 50, 50, 15);
        		regDateView.setBackgroundDrawable(shape);
        		
        		EditText contentView = new EditText(context);
        		contentView.setText(nd_array.get(i).getContent());
        		contentView.setTextColor(0xFF515151);
        		contentView.setPadding(20, 10, 20, 30);
        		contentView.setTextSize(15);
        		contentView.setFocusable(false);
        		LayoutParams params;
        		
        		params = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        		params.setMargins(10, 10, 10, 10);
        		mainNoticeView.addView(regDateView, params);
        		params = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        		mainNoticeView.addView(contentView, params);
            }
            */
        }

        @Override
		public void onCancel(DialogInterface dialog)
        {
        	cancel(true);
        	dialog.dismiss();
        }
	}
	
	
	private class getNewNotice extends AsyncTask<Void, Void, Void>{
		private Context context;
		
		private getNewNotice(Context context){
			this.context = context;
		}

		@Override
		protected void onPreExecute(){
			dialog.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				String param_seqno = "0";
				
				if(noticeJsonData.size() > 0){
					param_seqno = Integer.toString(noticeJsonData.get(noticeJsonData.size()-1).getSeqno());
				}
				
				Map<String, String> map = new HashMap<String, String>();
				map.put("curPageNo", param_seqno);

				JSONObject json = new JSONObject(hcm.readJSON_GET(getString(R.string.SERVER_URL) + "notice/notice_list.php", map));
				//JSONObject json_header = json.getJSONObject("header");
				JSONArray json_result = json.getJSONArray("data_result");
				
				
				//noticeJsonData.clear();
				
				for (int i = 0; i < json_result.length(); i++) {
					JSONObject jsonObject = json_result.getJSONObject(i);
					
					//if(jsonObject.getInt("seqno") == Integer.parseInt(param_seqno)){
					//	break;
					//}
					/*
					boolean dup = false;
					for(int j = 0 ; j < noticeJsonData.size(); j++){
						if(noticeJsonData.get(j).getSeqno() == jsonObject.getInt("seqno")){
							dup = true;
							break;
						}
					}
					
					if(dup)
						continue;
					*/
					
					NoticeData tmp_nd = new NoticeData();
					tmp_nd.setSeqno(jsonObject.getInt("seqno"));
					tmp_nd.setTitle(jsonObject.getString("title"));
					tmp_nd.setName(jsonObject.getString("name"));
					tmp_nd.setContent(jsonObject.getString("content"));
					tmp_nd.setReg_date(jsonObject.getString("reg_date"));
					tmp_nd.setReg_Check(jsonObject.getString("reg_check"));
					noticeJsonData.addLast(tmp_nd);
					Log.d("C2DM", "New Data: " + jsonObject.getInt("seqno"));
				}
				
				
				
				Log.d("C2DM", "THIS WILL BE SAVED:::::::: " + noticeJsonData.size());
				
				int initSize = 0;
				if(noticeJsonData.size() > 10)
					initSize = noticeJsonData.size() - 10;
				
				JSONArray tmp_result = new JSONArray();
				for(int i = initSize ; i < noticeJsonData.size() ; i++){
					JSONObject tmp_hash_result = new JSONObject();
					tmp_hash_result.put("seqno", Integer.toString(noticeJsonData.get(i).getSeqno()));
					tmp_hash_result.put("title", noticeJsonData.get(i).getTitle());
					tmp_hash_result.put("name", noticeJsonData.get(i).getName());
					tmp_hash_result.put("content", noticeJsonData.get(i).getContent());
					tmp_hash_result.put("reg_date", noticeJsonData.get(i).getReg_date());
					tmp_hash_result.put("reg_check", noticeJsonData.get(i).getReg_Check());
					tmp_result.put(tmp_hash_result);
				}
				
				Log.d("C2DM", "Saved Data to Preference: " + tmp_result.toString());
				
				JSONSharedPreferences.remove(context, "gline", "noticeInfo");
				JSONSharedPreferences.saveJSONArray(context, "gline", "noticeInfo", tmp_result);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused)
        {
			dialog.setVisibility(View.INVISIBLE);
			
			
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            Editor edit = prefs.edit();
            edit.putInt("noticeSeqno", prefs.getInt("noticeMaxSeqno",0)).commit();
            
            if(noticeJsonData != null && noticeJsonData.size() > 0){
            	noticeAdapter.notifyDataSetChanged();
            }
            
            noticeListView.setSelection(noticeJsonData.size()-1);
        }
	}
	
	
	private class getPrevNotice extends AsyncTask<Void, Void, Void>{
		private Context context;
		
		private getPrevNotice(Context context){
			this.context = context;
		}

		@Override
		protected void onPreExecute(){
			loadingBarLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				pageNo = (noticeJsonData != null ? noticeJsonData.size(): pageNo );
				
				Map<String, String> map = new HashMap<String, String>();
				map.put("pageNo", Integer.toString(pageNo));
				map.put("pageSize", Integer.toString(pageSize));
								
				JSONObject json = new JSONObject(hcm.readJSON_GET(getString(R.string.SERVER_URL) + "notice/notice_list.php", map));
				//JSONObject json_header = json.getJSONObject("header");
				JSONArray json_result;
				
				
				pageNo += pageSize;
				
				if(json.isNull("data_result")){
					isFinishedLoading = true;
					Log.e("C2DM", "Load Finished =========================");
				}else{
					json_result = json.getJSONArray("data_result");
					
					for (int i = json_result.length()-1; i >= 0; i--) {
						JSONObject jsonObject = json_result.getJSONObject(i);
						
						/*
						if(noticeJsonData.size() > 0 && jsonObject.getInt("seqno") == noticeJsonData.get(noticeJsonData.size()-1).getSeqno()){
							break;
						}
						*/
						
						NoticeData tmp_nd = new NoticeData();
						tmp_nd.setSeqno(jsonObject.getInt("seqno"));
						tmp_nd.setTitle(jsonObject.getString("title"));
						tmp_nd.setName(jsonObject.getString("name"));
						tmp_nd.setContent(jsonObject.getString("content"));
						tmp_nd.setReg_date(jsonObject.getString("reg_date"));
						tmp_nd.setReg_Check(jsonObject.getString("reg_check"));
						noticeJsonData.addFirst(tmp_nd);
						
						Log.d("C2DM", "Prev Data: " + jsonObject.getInt("seqno"));
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused){
        	loadingBarLayout.setVisibility(View.INVISIBLE);
        	
        	if(noticeJsonData != null && noticeJsonData.size() > 0){
            	noticeAdapter.notifyDataSetChanged();
            }
        	
        	if(firstPrevItemLoading){
        		noticeListView.setSelection(noticeJsonData.size()-1);
        		firstPrevItemLoading = false;
        	}else{
	        	if(isFinishedLoading)
	        		noticeListView.setSelection(0);
	        	else
	        		noticeListView.setSelection(pageSize+1);
        	}
        }
	}
	
	
	
	private class noticeListAdapter extends ArrayAdapter<NoticeData> {

        private LinkedList<NoticeData> items;

        public noticeListAdapter(Context context, int textViewResourceId, LinkedList<NoticeData> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.notice_listview_layout, null);
            }
            
            NoticeData p = items.get(position);
            
            if (p != null) {
                    TextView m1 = (TextView) v.findViewById(R.id.noticeTitle);
                    TextView m2 = (TextView) v.findViewById(R.id.noticeContent);
                    //TextView m3 = (TextView) v.findViewById(R.id.membBirth);
                    if(m1 != null)
                    	m1.setText(p.getName() + "    " + p.getReg_date());
                    if(m2 != null){
                    	m2.setText(p.getContent());
                    }
                    //if(m3 != null)
                    //m3.setText(p.getMemberBirth());
                    
            }
            return v;
        }
	}
	
	
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.menu, menu);// xml menu
		
		return true;
	}
	*/
	
	/*
	public boolean onOptionsItemSelected(MenuItem item){

		switch(item.getItemId()){
			case R.id.reLoad:
				new initPage(this).execute();
				break;
		}
		return false;
	}
	*/
	/*
	public void onScrollStateChanged(View view, int scrollState) {
        if (mIsLoading) {
            return;
        }
        switch (scrollState) {
        case SCROLL_STATE_IDLE:
            if (view.getLastVisiblePosition() >= mTotalItemCount - 1 && mTotalItemCount > 0) {
                if (getListView().getFooterViewsCount() == 1 && !mIsLoading) {
                    mIsLoading = true;
                    //setProgressBarIndeterminateVisibility(true);
                    mListFooter.setVisibility(View.VISIBLE);
                    Thread thread = new Thread(mLoadListItems);
                    thread.start();
                }
            }
            break;
        case SCROLL_STATE_TOUCH_SCROLL:
            break;
        case SCROLL_STATE_FLING:
            break;
        }
    }
    */
	
	
	/*

	public class array3 {
	    public static void main(String[] args) {
	        int ar3[]={33,45,67,87,34,56};
	        int ar4[]={5,8,9,22,3,4};
	        List list1=new ArrayList();
	        List list2=new ArrayList();
	         for (int i = 0; i < ar3.length; i++) {
	            list1.add(ar3[i]);
	        }
	   for (int i = 0; i < ar4.length; i++) {
	            list2.add(ar4[i]);
	        }
	        list1.addAll(list2);
	        System.out.println(list);           
	    }
	}
	 
	 
	*/


}

